package com.zhongxi.guoyuan.view.personalCenter;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.personCenter.ExchangePayAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.ClearPayResult;
import com.zhongxi.guoyuan.entity.coinStore.AddressDefaultData;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.NoPayAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostDefaultAddress;
import com.zhongxi.guoyuan.entity.coinStore.PostcartAttrsCollection;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.shopcart.RewardSummary;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.utils.PayUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.rewardCoin.CustomerNotesActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardAddressListActivity;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;
import com.zhongxi.guoyuan.zhifubao.PayResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ExchangePayActivity extends BaseActivity implements View.OnClickListener {


    private TextView tv_total_postage;
    private TextView tv_edit_address;
    private TextView tvUserName;
    private TextView tvAddress;
    private TextView tvPhone;
    private ExchangePayAdapter adapter;
    private IWXAPI msgApi;
    private PayReq req;
    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        showAlipaySuccessResult();
                    } else {
                        showAlipayResult(1);
                    }
                    break;
            }
        }
    };


    private NoScrollListView listView;
    private ImageView iv_weixin;
    private ImageView iv_zhifubao;
    private RelativeLayout rl_address_info;
    private RelativeLayout relaReceiver;
    private String str = "{";
    private String truetotalPrice = "0.00";
    private String type;
    private String orderId;
    private int index = -1;
    //    private PayParamsResult paramsResult;
    private RewardSummary rewardSummary;
    private AttrsSelect attrs;
    private ArrayList<PostcartAttrsCollection> goodsList;
    private String HD = "0.00";
    private String MD = "0.00";
    private String totalPost = "0";
    private int payType = 0;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;

    private TextView tvTrueInner;
    private TextView tvTrueRedBean;
    private TextView tvNowSave;

    private EditText etPwd;
    private TextView btnPay;

    private String totalInnerPrice = "0";
    private String totalRedBean = "0";
    private String totalPrice = "0";
    private String totalTruePost = "0";
    private UserExtendResult extendResult;
    private String mVerifycode;
    private String mTrim;
    private String payResultOrderid;
    private TextView tvReward;

    private String goodsNumRed = "0";
    private String totalAwardCash;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_exchange_pay);
        initTitle();
        tvTitle.setText("豆豆兑换确认");
        if (getIntent().getExtras() != null) {
            goodsList = (ArrayList<PostcartAttrsCollection>) getIntent().getExtras().getSerializable("goodsInfo");
            payType = getIntent().getExtras().getInt("post", 0);     // 1 为邮寄   0 为 自提   2. 同城免邮
        }
        if (getIntent() != null) {
            orderId = getIntent().getStringExtra("orderId");  //个人中心的未支付订单
        }
        if (getIntent() != null) {
            attrs = (AttrsSelect) getIntent().getSerializableExtra("attrs");  //立即支付
            payType = getIntent().getIntExtra("post", 0);    // 1 有邮寄地址  0 无  2. 同城免邮
        }
        tv_edit_address = (TextView) findViewById(R.id.tv_edit_address);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        listView = (NoScrollListView) findViewById(R.id.listView);

        tv_total_postage = (TextView) findViewById(R.id.tv_total_postage);
        iv_weixin = (ImageView) findViewById(R.id.iv_weixin);
        iv_zhifubao = (ImageView) findViewById(R.id.iv_zhifubao);
        rl_address_info = (RelativeLayout) findViewById(R.id.rl_address_info);
        relaReceiver = (RelativeLayout) findViewById(R.id.relaReceiver);
        tvTrueInner = (TextView) findViewById(R.id.exchange_pay_price);
        tvTrueRedBean = (TextView) findViewById(R.id.exchange_pay_redbean);
        tvNowSave = (TextView) findViewById(R.id.exchange_pay_nowsave);
        etPwd = (EditText) findViewById(R.id.exchange_pay_existing);
        btnPay = (TextView) findViewById(R.id.exchange_pay_sure);
        tvReward= (TextView) findViewById(R.id.exchange_pay_reward);
        if (1 == payType || payType == 2) {
            rl_address_info.setVisibility(View.VISIBLE);
        } else {
            rl_address_info.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        if (1 == payType) {
            if (null != attrs.getAmountofmail() && !"".equals(attrs.getAmountofmail()) && !"0".equals(attrs.getAmountofmail())) {
                if (DataUtil.moreThanOther(DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2), attrs.getAmountofmail())) {

                    totalInnerPrice = DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2);
                    totalRedBean = DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2);

                    totalPost = "0";
                } else {

                    totalInnerPrice = DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2);
                    totalRedBean = DataUtil.add(DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2), attrs.getPostage());
//                        totalRedBean= DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2);
                    totalPost = attrs.getPostage();
                }
            } else {

                totalInnerPrice = DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2);
                totalRedBean = DataUtil.add(DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2), attrs.getPostage());
//                    totalRedBean= DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2);
                totalPost = attrs.getPostage();
            }
            goodsNumRed = DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2);
        } else {
            totalPost = "0";
            totalInnerPrice = DataUtil.multiplys(attrs.getPrice(), attrs.getGoodsnum(), 2);
            totalRedBean = DataUtil.multiplys(attrs.getRedprice(), attrs.getGoodsnum(), 2);
        }


        //实际需支付的美豆数，红豆数
        if (DataUtil.moreThanZero(totalInnerPrice) && DataUtil.moreThanZero(totalRedBean)) {
            tvTrueInner.setText(CommonTool.getWhole(totalInnerPrice) + "美豆");
            tvTrueRedBean.setText("+" + CommonTool.getWhole(totalRedBean) + "红豆");

            tvReward.setVisibility(View.VISIBLE);
            if(null!=attrs.getBackcashnum()&&!"".equals(attrs.getBackcashnum())&&DataUtil.moreThanZero(attrs.getBackcashnum())){
                totalAwardCash = CommonTool.getWhole(DataUtil.multiplys(attrs.getBackcashnum(), attrs.getGoodsnum(), 2));
                tvReward.setText("（红豆不够现金补，兑成奖："+ totalAwardCash +"元）");
            }else{
                tvReward.setText("（红豆不够现金补）");
            }
        } else if (DataUtil.moreThanZero(totalInnerPrice) && !DataUtil.moreThanZero(totalRedBean)) {
            tvTrueInner.setText(CommonTool.getWhole(totalInnerPrice) + "美豆");
            tvTrueRedBean.setText("");
            tvReward.setVisibility(View.GONE);
        } else if (!DataUtil.moreThanZero(totalInnerPrice) && DataUtil.moreThanZero(totalRedBean)) {
            tvTrueInner.setText("");
            tvTrueRedBean.setText(CommonTool.getWhole(totalRedBean) + "红豆");
            tvReward.setVisibility(View.GONE);
        }else {
            tvReward.setVisibility(View.GONE);
        }


        String now = "您目前现存：" + MyApplication.getInstance().getInnerCurrency() + " 美豆/" + MyApplication.getInstance().getHdCurrency() + "红豆";
        tvNowSave.setText(now);

        //美豆不够
        if (!DataUtil.moreThanOther(MyApplication.getInstance().getInnerCurrency(), totalInnerPrice)) {
            showMiedouNoEnough();
        }

        String mycurrent = MyApplication.getInstance().getHdCurrency();
        if (mycurrent.equals("")) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "0").commit();
        }
        if (DataUtil.moreThanOther(totalRedBean, MyApplication.getInstance().getHdCurrency())) {
            totalPrice = DataUtil.subtract(totalRedBean, MyApplication.getInstance().getHdCurrency());
            totalRedBean = MyApplication.getInstance().getHdCurrency();
        }


        adapter = new ExchangePayAdapter(this, goodsList, attrs, payType);
        listView.setAdapter(adapter);
        getAddressInfo();
    }

    /***
     * 美豆不够
     */
    private void showMiedouNoEnough() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_noenough, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
    }

    private void showAlipayResult(int i) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_noenough, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);

        TextView tvContent = (TextView) layout.findViewById(R.id.tvContent);
        TextView tvContent2 = (TextView) layout.findViewById(R.id.tvContent2);

        if (i == 1) {
            tvContent.setText(getString(R.string.exchangeNoSuccessTip));
            tvContent2.setText(getString(R.string.exchangeNoSuccessContent));
        }
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });

    }

    private void showAlipaySuccessResult() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_paysuccess, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);


        TextView tvContent2 = (TextView) layout.findViewById(R.id.tvContent2);
        if (!totalRedBean.equals("0"))
            tvContent2.setText("奖励您 " + totalAwardCash + " 元");
        else
            tvContent2.setText(getString(R.string.exchangeSuccessContent));

        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);


        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });

    }

    private void getAddressInfo() {
        if (orderId != null && !"".equals(orderId)) {
            PostcartAttrsCollection postcartAttrsCollection = goodsList.get(0);
            if (null != postcartAttrsCollection.getAddress() && !"".equals(postcartAttrsCollection.getAddress())) {
                NoPayAddress address = postcartAttrsCollection.getAddress();
                relaReceiver.setVisibility(View.VISIBLE);
                tvUserName.setText(address.getName());
                tvPhone.setText(address.getPhone());
                tvAddress.setText(address.getAddress());
            } else {
                getPresonIfo();
            }
        } else {
            getPresonIfo();
        }
    }

    private void getPresonIfo() {
        if (TextUtils.isEmpty(MyApplication.getInstance().getRewardAddressid())) {
//            relaReceiver.setVisibility(View.GONE);
            relaReceiver.setVisibility(View.VISIBLE);
            getDefaultAddress();
        } else {
            relaReceiver.setVisibility(View.VISIBLE);
            tvUserName.setText(MyApplication.getInstance().getRewardName());
            tvPhone.setText(MyApplication.getInstance().getRewardUserPhone());
            tvAddress.setText(MyApplication.getInstance().getRewardAddress());
        }
    }

    private void getDefaultAddress() {
        type = "defaultAddress";
        getServer(Url.REWARD_DEFAULT_ADDRESS, null, "", false, null, "get");
    }

    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String strs = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tv_edit_address.setOnClickListener(this);
        iv_weixin.setOnClickListener(this);
        iv_zhifubao.setOnClickListener(this);
        btnPay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.exchange_pay_sure:

                mTrim = etPwd.getText().toString().trim();
                if (mTrim != null && mTrim.length() > 0) {
                    //1邮寄 0自提
                    if (payType == 1) {
                        if ("".equals(MyApplication.getInstance().getRewardAddressid())) {
                            showShortToast("请选择邮寄地址");
                        } else {
                            if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                                verifyCode();
                            }else {
                                ToastUtil.show("您还没有绑定手机号,暂不能支付");
                            }
                        }
                    } else {
                        if (!TextUtils.isEmpty(MyApplication.getInstance().getPhone())) {
                            verifyCode();
                        }else {
                            ToastUtil.show("您还没有绑定手机号,暂不能支付");
                        }
                    }
                }
                break;
            case R.id.tv_edit_address:
                Intent intent = new Intent(context, RewardAddressListActivity.class);
                startActivityForResult(intent, 100);
                break;

        }
    }

    /**
     * 获取支付码后判断红豆是否足够
     */
    private void requestVf() {
        if (!DataUtil.moreThanZero(totalPrice)) {
            rightNowPay();
        } else {
            showHongdouNoBalance();
        }
    }

    /**
     * 红豆余额不足
     */
    private void showHongdouNoBalance() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_order_hongdou, null);
        final android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView order_tvLess_hongdou = (TextView) layout.findViewById(R.id.order_tvLess_hongdou);
        order_tvLess_hongdou.setText(CommonTool.getWhole(totalPrice) + " 红豆");
        TextView order_tvLess_yuan = (TextView) layout.findViewById(R.id.order_tvLess_yuan);
        order_tvLess_yuan.setText(CommonTool.getWhole(totalPrice) + " 元");
        LinearLayout ll_aliPay = (LinearLayout) layout.findViewById(R.id.ll_aliPay);
        ll_aliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    rightNowPay();
                    index = 1;
                }
                dialog.dismiss();
            }
        });
        LinearLayout ll_weichatPay = (LinearLayout) layout.findViewById(R.id.ll_weichatPay);
        ll_weichatPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    rightNowPay();
                    index = 0;
                }
                dialog.dismiss();
            }
        });
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

    }

    /**
     * 支付校验
     */
    private void verifyCode() {
        type = "verifyCode";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    private void rightNowPay() {
        type = "topay";
        Map<String, String> map = new HashMap<>();
        map.put("shopid", attrs.getShopId());
        map.put("goodsid", attrs.getGoodsid());
        map.put("goodsnum", attrs.getGoodsnum());
        map.put("collectionid", attrs.getId());
        map.put("attrlist", attrs.getAttrlist());
        if (!TextUtils.isEmpty(attrs.getCustomNotes())) {
            map.put("remark", attrs.getCustomNotes());
        }
//        paytype=1邮寄  0自提
        if (1 == payType) {
            map.put("shippingid", MyApplication.getInstance().getRewardAddressid());
            map.put("getermethod", "1");
        } else {
            map.put("getermethod", "2");
        }
        map.put("innerprice", CommonTool.getWhole(totalInnerPrice));

        //如果当前红豆大于商品需支付的红豆
        if (DataUtil.moreThanOtherNoEqual(MyApplication.getInstance().getHdCurrency(), goodsNumRed)) {
            totalRedBean = CommonTool.getWhole(DataUtil.subtract(totalRedBean, totalPost));
            map.put("redbean", totalRedBean);
            map.put("postage", totalPost);
        } else {
            totalRedBean = CommonTool.getWhole(totalRedBean);
            totalPost = "0";
            map.put("redbean", totalRedBean);
            map.put("postage", totalPost);
        }

        map.put("price", CommonTool.getWhole(totalPrice));
        map.put("verifycode", mVerifycode);
        map.put("pwd", MyApplication.getInstance().descsc(mTrim));

        for (String key : map.keySet()) {
            Log.d("flag", "rightNowPay: key:" + key + ":" + map.get(key));
        }

        getServer(Url.EXCHANGE_PAY, map, "", false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("defaultAddress".equals(type)) {
                PostDefaultAddress defaultAddress = gson.fromJson(response, PostDefaultAddress.class);
                MyApplication.getInstance().setSpValue(defaultAddress.getSafeobj());
                if (defaultAddress.getData() != null && !"".equals(defaultAddress.getData())) {
                    AddressDefaultData data = defaultAddress.getData();
                    if (data.getId() != null && !"".equals(data.getId())) {
                        relaReceiver.setVisibility(View.VISIBLE);
                        String addressId = data.getId();
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", addressId).commit();
                        String address = "";
                        if (data.getProvince() != null && !"".equals(data.getProvince())) {
                            address += data.getProvince();
                        }
                        if (data.getCity() != null && !"".equals(data.getCity())) {
                            address += data.getCity();
                        }
                        if (data.getPrefecture() != null && !"".equals(data.getPrefecture())) {
                            address += data.getPrefecture();
                        }
                        if (data.getAddress() != null && !"".equals(data.getAddress())) {
                            address += data.getAddress();
                        }
                        tvAddress.setText("地址:" + address);
                        MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", address).commit();
                        if (data.getUsername() != null && !"".equals(data.getUsername())) {
                            tvUserName.setText(data.getUsername());
                            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", data.getUsername()).commit();
                        }
                        if (data.getMphone() != null && !"".equals(data.getMphone())) {
                            tvPhone.setText(data.getMphone());
                            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", data.getMphone()).commit();
                        }
                    } else {
//                        relaReceiver.setVisibility(View.GONE);
                        relaReceiver.setVisibility(View.VISIBLE);
                    }
                } else {
//                    relaReceiver.setVisibility(View.GONE);
                    relaReceiver.setVisibility(View.VISIBLE);
                }
            } else if (type.equals("verifyCode")) {
                extendResult = gson.fromJson(response, UserExtendResult.class);
                MyApplication.getInstance().setSpValue(extendResult.getSafeobj());
                if (null != extendResult.getVerifycode() && !"".equals(extendResult.getVerifycode())) {
                    mVerifycode = extendResult.getVerifycode();
                    requestVf();
                } else {
                    showShortToast("支付校验失败");
                }
            } else if ("topay".equals(type)) {
                ClearPayResult payResult = gson.fromJson(response, ClearPayResult.class);
                MyApplication.getInstance().setSpValue(payResult.getSafeobj());
                if (null != payResult && !"".equals(payResult)) {
                    payResultOrderid = payResult.getOrderid();

                    String securityKey = payResult.getSecurityKey();
                    if (null != securityKey && !"".equals(securityKey)) {
                        String payParams = parseSecutiryKey(securityKey);
                        try {
                            JSONObject jsonObject = new JSONObject(payParams);
                            JSONObject alipay = jsonObject.optJSONObject("alipay");
                            aliPayData = PayAliPayData.parseObject(alipay);
                            JSONObject wechat = jsonObject.optJSONObject("wechat");
                            weixinData = WeixinData.parseObject(wechat);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "exchange").commit();

                        if (index == 0) {//微信支付
                            MyApplication.getInstance().sharedPrefrences.edit().putString("payredbean", totalAwardCash).commit();
                            weixinPayRequest(weixinData);
                        } else if (index == 1) {//支付宝支付
                            zhifubaoPayRequest(aliPayData);
                        }
                    } else {
                        showAlipaySuccessResult();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            JSONObject mJSONObject=new JSONObject(response);
            if (1000 == result.getCode()) {
                showShortToast("参数错误");
            } else if (1557 == result.getCode()) {
                showShortToast("数量超限");
            } else if (1669 == result.getCode()) {
                showShortToast("红豆不足");
            } else if (2001 == result.getCode()) {
                showShortToast("库存不足");
            } else if (2005 == result.getCode()) {
                showShortToast("商品与 商品集合不匹配");
            } else if (2006 == result.getCode()) {
                showShortToast("商品集合数据格式错误");  //商品集合数据格式错误
            } else if (2007 == result.getCode()) {
                showShortToast("商品属性不在指定集合中");
            } else if (2008 == result.getCode()) {
                showShortToast("商品属性数据丢失， 请管理员调整");
            } else if (2009 == result.getCode()) {
                showShortToast("商品属性选择不完整");
            } else if (2013 == result.getCode()) {
                showShortToast("邮费错误");
            } else if (2015 == result.getCode()) {
                showShortToast("订单镜像丢失");
            } else if (2016 == result.getCode()) {
                showShortToast("订单定制信息已丢失");
            } else if (2019 == result.getCode()) {
                String mLastnum = mJSONObject.optString("lastnum");

                showShortToast("抱歉，当日该商品您的兑换次数还剩"+mLastnum+"次");
            } else if (2021 == result.getCode()) {
                String mLastnum = mJSONObject.optString("lastnum");

                showShortToast("抱歉，该商品总兑换次数还剩"+mLastnum+"次");
            } else if (4003 == result.getCode()) {
                showShortToast("密码错误");
            } else if (5003 == result.getCode()) {
                showShortToast("美豆不足");
            } else if (5019 == result.getCode()) {
                showShortToast("选购商品数量超过库存");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void zhifubaoPayRequest(PayAliPayData alipay) {
        PayUtils payUtils = new PayUtils(payResultOrderid, attrs.getName(), 6, CommonTool.getWhole(totalInnerPrice), CommonTool.getWhole(totalRedBean), totalPost, CommonTool.getWhole(totalPrice));
        payUtils.zhifubaoPay(alipay, mHandler, ExchangePayActivity.this);
    }


    public void weixinPayRequest(WeixinData weixinData) {
        PayUtils payUtils = new PayUtils(payResultOrderid, attrs.getName(), 6, CommonTool.getWhole(totalInnerPrice), CommonTool.getWhole(totalRedBean)
                , totalPost, CommonTool.getWhole(totalPrice), this, weixinData);
        payUtils.weixinPay();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == 0) {
            getPresonIfo();
        } else if (requestCode == 100 && resultCode == RewardAddressListActivity.RESULTCODEADDRESS) {
            if (null != MyApplication.getInstance().getRewardAddressid() && !"".equals(MyApplication.getInstance().getRewardAddressid())) {
                relaReceiver.setVisibility(View.VISIBLE);
                tvUserName.setText(MyApplication.getInstance().getRewardName());
                tvPhone.setText(MyApplication.getInstance().getRewardUserPhone());
                tvAddress.setText(MyApplication.getInstance().getRewardAddress());
            } else {
//                relaReceiver.setVisibility(View.GONE);
                relaReceiver.setVisibility(View.VISIBLE);
            }
        } else if (requestCode == adapter.REQUESTNOTESCODE && resultCode == CustomerNotesActivity.RESULTNOTESCODE) {
            String mNotes = data.getStringExtra("notes");
            String mShopid = data.getStringExtra("shopid");
            if (goodsList != null && goodsList.size() > 0) {
                for (int i = 0; i < goodsList.size(); i++) {
                    if (goodsList.get(i).getShopInfos().getId().equals(mShopid)) {
                        goodsList.get(i).setCustomNotes(mNotes);
                    }
                }
            } else {
                if (attrs.getShopId().equals(mShopid)) {
                    attrs.setCustomNotes(mNotes);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }
}
